// 共享数据模型定义文件

// ============== 基础类型定义 ==============

// 阶段类型
export type StageLevel = 'freshman' | 'sophomore' | 'junior';

// 学院类型
export type AcademyType = '人工智能' | '数智传媒' | '鸿蒙生态开发' | '云计算' | '元宇宙' | '市场部' | '中原市场部' | '辽冀市场部' | '石家庄市场部' | '黑冀市场部' | '保沧市场部';

// 学院选项
export const academyOptions = [
  { value: '人工智能' as AcademyType, label: '人工智能' },
  { value: '数智传媒' as AcademyType, label: '数智传媒' },
  { value: '鸿蒙生态开发' as AcademyType, label: '鸿蒙生态开发' },
  { value: '云计算' as AcademyType, label: '云计算' },
  { value: '元宇宙' as AcademyType, label: '元宇宙' },
  { value: '市场部' as AcademyType, label: '市场部' },
  { value: '中原市场部' as AcademyType, label: '中原市场部' },
  { value: '辽冀市场部' as AcademyType, label: '辽冀市场部' },
  { value: '石家庄市场部' as AcademyType, label: '石家庄市场部' },
  { value: '黑冀市场部' as AcademyType, label: '黑冀市场部' },
  { value: '保沧市场部' as AcademyType, label: '保沧市场部' }
];

// 市场部列表 - 用于判断学生是否属于任何市场部
export const marketingDepartments = [
  '市场部',
  '中原市场部',
  '辽冀市场部',
  '石家庄市场部',
  '黑冀市场部',
  '保沧市场部'
];

// 学生状态
export type StudentStatus = 'active' | 'graduated' | 'transferred' | 'suspended';

// 教师状态
export type TeacherStatus = 'active' | 'leave' | 'retired';

// 考勤状态
export type AttendanceStatus = 'present' | 'absent' | 'late';

// 日志状态
export type LogStatus = 'success' | 'failed' | 'warning';

// 宿舍类型
export type DormitoryType = 'male' | 'female';

// 宿舍状态
export type DormitoryStatus = 'active' | 'maintenance' | 'closed';

// ============== 核心实体定义 ==============

// 学生实体
export interface Student {
  id: string;            // 统一使用字符串ID
  name: string;
  studentId: string;     // 学号
  gender: 'male' | 'female';
  stage: StageLevel;     // 阶段
  academy: AcademyType;  // 学院
  classId: string;       // 班级ID，关联到Class表
  dormitoryId?: string;  // 宿舍ID，关联到Dormitory表
  dateOfBirth: string;
  admissionDate: string;
  phoneNumber: string;
  email: string;
  address: string;
  status: StudentStatus; // 学生状态
  avatar?: string;       // 头像URL
  emergencyContact?: {
    name: string;
    relationship: string;
    phone: string;
  };
}

// 教师实体
export interface Teacher {
  id: string;            // 统一使用字符串ID
  name: string;
  teacherId: string;     // 工号
  gender: 'male' | 'female';
  subject: string;       // 科目
  stage: StageLevel;     // 教授阶段
  academy: AcademyType;  // 所属学院
  position: string;      // 职位（教师、班主任、主任等）
  education: string;     // 学历
  dateOfBirth: string;
  hireDate: string;      // 入职日期
  phoneNumber: string;
  email: string;
  address: string;
  status: TeacherStatus; // 教师状态
  avatar?: string;       // 头像URL
  department: string;    // 部门/教研组
  salaryLevel?: string;  // 薪资等级
  qualifications?: string[]; // 资格证书
}

// 班级实体
export interface Class {
  id: string;            // 统一使用字符串ID
  name: string;          // 班级名称
  stage: ExtendedStageLevel;     // 阶段
  academy: AcademyType;  // 所属学院
  headTeacherId: string; // 班主任ID，关联到Teacher表
  studentCount: number;  // 学生数量（派生字段，可实时计算）
  subjects: string[];    // 开设科目
  status: string;        // 状态
  createdAt: string;     // 创建时间
  updatedAt: string;     // 更新时间
}

// 宿舍实体
export interface Dormitory {
  id: string;            // 统一使用字符串ID
  building: string;      // 楼栋名称
  roomNumber: string;    // 房间号
  type: DormitoryType;   // 宿舍类型（男/女/混合）
  capacity: number;      // 容量
  currentOccupancy: number; // 当前入住人数
  students: string[];    // 入住学生ID列表
  floor: number;         // 楼层
  supervisor?: string;   // 宿舍管理员
  phoneNumber?: string;  // 联系电话
  status: DormitoryStatus; // 宿舍状态
  createdAt: string;     // 创建时间
  updatedAt: string;     // 更新时间
  notes?: string;        // 备注
}

// 成绩实体
export interface Grade {
  id: string;           // 唯一标识
  term: string;         // 学期
  examType: string;     // 考试类型
  studentId: string;    // 学生ID，关联到Student表
  subject: string;      // 科目
  score: number;        // 分数
  rank?: number;        // 排名
  remark?: string;      // 备注
  createdBy?: string;   // 创建人
  createdAt?: string;   // 创建时间
  updatedBy?: string;   // 更新人
  updatedAt?: string;   // 更新时间
}

// 考勤实体
export interface Attendance {
  id: string;           // 唯一标识
  date: string;         // 考勤日期
  studentId: string;    // 学生ID，关联到Student表
  classId: string;      // 班级ID，关联到Class表
  status: AttendanceStatus; // 考勤状态
  remark?: string;      // 备注
  createdBy?: string;   // 创建人
  createdAt?: string;   // 创建时间
  updatedBy?: string;   // 更新人
  updatedAt?: string;   // 更新时间
}

// 审计日志实体
export interface AuditLog {
  id: string;
  timestamp: string;
  userId: string;       // 用户ID
  user: string;         // 用户名
  action: string;       // 操作类型
  module: string;       // 模块名称
  moduleId?: string;    // 操作的具体实体ID
  details: string;      // 详细信息
  ipAddress: string;    // IP地址
  status: LogStatus;    // 操作状态
}

// ============== 选项数据共享 ==============

// 阶段选项（统一使用）
export const stageOptions = [
  { value: 'freshman' as StageLevel, label: '专业阶段' },
  { value: 'sophomore' as StageLevel, label: '专高阶段' },
  { value: 'junior' as StageLevel, label: '实训阶段' },
  { value: 'zhuangao1' as any, label: '专高阶段一' },
  { value: 'zhuangao2' as any, label: '专高阶段二' },
  { value: 'zhuangao3' as any, label: '专高阶段三' },
  { value: 'zhuangao4' as any, label: '专高阶段四' },
  { value: 'zhuangao5' as any, label: '专高阶段五' },
  { value: 'zhuangao6' as any, label: '专高阶段六' },
  { value: 'shixun1' as any, label: '实训阶段一' },
  { value: 'shixun2' as any, label: '实训阶段二' },
  { value: 'shixun3' as any, label: '实训阶段三' }
];

// 扩展StageLevel类型
export type ExtendedStageLevel = StageLevel | 'zhuangao1' | 'zhuangao2' | 'zhuangao3' | 'zhuangao4' | 'zhuangao5' | 'zhuangao6' | 'shixun1' | 'shixun2' | 'shixun3';

// 科目选项（统一使用）
export const subjectOptions = [
  { value: 'chinese', label: '语文', maxScore: 150 },
  { value: 'math', label: '数学', maxScore: 150 },
  { value: 'english', label: '英语', maxScore: 150 },
  { value: 'physics', label: '物理', maxScore: 100 },
  { value: 'chemistry', label: '化学', maxScore: 100 },
  { value: 'biology', label: '生物', maxScore: 100 },
  { value: 'history', label: '历史', maxScore: 100 },
  { value: 'geography', label: '地理', maxScore: 100 },
  { value: 'politics', label: '政治', maxScore: 100 },
  { value: 'music', label: '音乐', maxScore: 100 },
  { value: 'art', label: '美术', maxScore: 100 },
  { value: 'pe', label: '体育', maxScore: 100 },
  { value: 'it', label: '信息技术', maxScore: 100 }
];

// 学生状态选项
export const studentStatusOptions = [
  { value: 'active' as StudentStatus, label: '在读' },
  { value: 'graduated' as StudentStatus, label: '毕业' },
  { value: 'transferred' as StudentStatus, label: '转学' },
  { value: 'suspended' as StudentStatus, label: '休学' }
];

// 教师状态选项
export const teacherStatusOptions = [
  { value: 'active' as TeacherStatus, label: '在职' },
  { value: 'leave' as TeacherStatus, label: '请假' },
  { value: 'retired' as TeacherStatus, label: '退休' }
];

// 考勤状态选项
export const attendanceStatusOptions = [
  { value: 'present' as AttendanceStatus, label: '出勤', color: 'green' },
  { value: 'absent' as AttendanceStatus, label: '缺勤', color: 'red' },
  { value: 'late' as AttendanceStatus, label: '迟到', color: 'orange' }
];

// 宿舍类型选项
export const dormitoryTypeOptions = [
  { value: 'male' as DormitoryType, label: '男生宿舍' },
  { value: 'female' as DormitoryType, label: '女生宿舍' }
];

// 宿舍状态选项
export const dormitoryStatusOptions = [
  { value: 'active' as DormitoryStatus, label: '正常使用', color: 'green' },
  { value: 'maintenance' as DormitoryStatus, label: '维修中', color: 'orange' },
  { value: 'closed' as DormitoryStatus, label: '已关闭', color: 'red' }
];

// ============== 工具函数 ==============

// 数据关联工具函数
export const dataUtils = {
  // 获取班级的导员信息
  getAdvisor: (classId: string, classes: Class[], teachers: Teacher[]): Teacher | undefined => {
    const cls = classes.find(c => c.id === classId);
    return cls ? teachers.find(t => t.id === cls.advisorId) : undefined;
  },
  
  // 获取班级的讲师信息
  getLecturer: (classId: string, classes: Class[], teachers: Teacher[]): Teacher | undefined => {
    const cls = classes.find(c => c.id === classId);
    return cls ? teachers.find(t => t.id === cls.lecturerId) : undefined;
  },

  // 获取学生所在班级信息
  getStudentClass: (studentId: string, students: Student[], classes: Class[]): Class | undefined => {
    const student = students.find(s => s.id === studentId);
    return student ? classes.find(c => c.id === student.classId) : undefined;
  },

  // 获取班级所有学生
  getClassStudents: (classId: string, students: Student[]): Student[] => {
    return students.filter(s => s.classId === classId && s.status === 'active');
  },

  // 获取教师作为导员管理的班级
  getAdvisorClasses: (teacherId: string, classes: Class[]): Class[] => {
    return classes.filter(c => c.advisorId === teacherId);
  },
  
  // 获取教师作为讲师的班级
  getLecturerClasses: (teacherId: string, classes: Class[]): Class[] => {
    return classes.filter(c => c.lecturerId === teacherId);
  },

  // 计算班级学生数量
  updateClassStudentCount: (classes: Class[], students: Student[]): Class[] => {
    return classes.map(cls => ({
      ...cls,
      studentCount: students.filter(s => s.classId === cls.id && s.status === 'active').length
    }));
  },

  // 验证数据一致性
  validateDataConsistency: (data: {
    students: Student[];
    teachers: Teacher[];
    classes: Class[];
    grades?: Grade[];
    attendances?: Attendance[];
  }): { isValid: boolean; errors: string[] } => {
    const errors: string[] = [];

    // 验证班级的导员ID是否存在
    data.classes.forEach(cls => {
      if (!data.teachers.some(t => t.id === cls.advisorId)) {
        errors.push(`班级 ${cls.name} 的导员ID ${cls.advisorId} 不存在`);
      }
      // 验证班级的讲师ID是否存在
      if (!data.teachers.some(t => t.id === cls.lecturerId)) {
        errors.push(`班级 ${cls.name} 的讲师ID ${cls.lecturerId} 不存在`);
      }
    });

    // 验证学生的班级ID是否存在
    data.students.forEach(student => {
      if (!data.classes.some(c => c.id === student.classId)) {
        errors.push(`学生 ${student.name} (${student.studentId}) 的班级ID ${student.classId} 不存在`);
      }
    });

    // 验证成绩记录的学生ID是否存在
    if (data.grades) {
      data.grades.forEach(grade => {
        if (!data.students.some(s => s.id === grade.studentId)) {
          errors.push(`成绩记录的学生ID ${grade.studentId} 不存在`);
        }
      });
    }

    // 验证考勤记录的学生ID和班级ID是否存在
    if (data.attendances) {
      data.attendances.forEach(attendance => {
        if (!data.students.some(s => s.id === attendance.studentId)) {
          errors.push(`考勤记录的学生ID ${attendance.studentId} 不存在`);
        }
        if (!data.classes.some(c => c.id === attendance.classId)) {
          errors.push(`考勤记录的班级ID ${attendance.classId} 不存在`);
        }
      });
    }

    return {
      isValid: errors.length === 0,
      errors
    };
  },

  // 生成关联数据的缓存键
  generateCacheKey: (entityType: string, id: string): string => {
    return `${entityType}:${id}`;
  },

  // 获取关联实体的显示名称
  getDisplayName: (entity: any, type: string): string => {
    switch (type) {
      case 'student':
        return entity.name || `学生${entity.studentId || entity.id}`;
      case 'teacher':
        return entity.name || `教师${entity.teacherId || entity.id}`;
      case 'class':
        return entity.name || `班级${entity.id}`;
      case 'dormitory':
        return `${entity.building} ${entity.roomNumber}` || `宿舍${entity.id}`;
      default:
        return entity.name || entity.id;
    }
  },

  // 获取宿舍中的学生
  getDormitoryStudents: (dormitoryId: string, students: Student[]): Student[] => {
    return students.filter(s => s.dormitoryId === dormitoryId && s.status === 'active');
  },

  // 更新宿舍入住人数
  updateDormitoryOccupancy: (dormitories: Dormitory[], students: Student[]): Dormitory[] => {
    return dormitories.map(dorm => ({
      ...dorm,
      currentOccupancy: students.filter(s => 
        s.dormitoryId === dorm.id && 
        s.status === 'active'
      ).length
    }));
  },

  // 更新宿舍学生列表
  updateDormitoryStudents: (dormitories: Dormitory[], students: Student[]): Dormitory[] => {
    return dormitories.map(dorm => ({
      ...dorm,
      students: students
        .filter(s => s.dormitoryId === dorm.id && s.status === 'active')
        .map(s => s.id)
    }));
  },

  // 获取空闲宿舍
  getAvailableDormitories: (dormitories: Dormitory[]): Dormitory[] => {
    return dormitories.filter(d => 
      d.status === 'active' && d.currentOccupancy < d.capacity
    );
  },

  // 根据宿舍类型过滤宿舍
  filterDormitoriesByType: (dormitories: Dormitory[], type: DormitoryType | 'all'): Dormitory[] => {
    if (type === 'all') return dormitories;
    return dormitories.filter(d => d.type === type);
  }
};

// ============== 数据存储接口 ==============

// 数据存储接口定义
export interface DataStorage<T> {
  getAll: () => Promise<T[]>;
  getById: (id: string) => Promise<T | undefined>;
  create: (item: Omit<T, 'id' | 'createdAt' | 'updatedAt'>) => Promise<T>;
  update: (id: string, item: Partial<T>) => Promise<T>;
  delete: (id: string) => Promise<boolean>;
  search: (query: any) => Promise<T[]>;
}

// 数据变更通知接口
export interface DataChangeNotifier {
  subscribe: (callback: (entityType: string, changeType: string, entityId: string) => void) => () => void;
  notify: (entityType: string, changeType: string, entityId: string) => void;
}